package com.ckd.flyingtrip.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import androidx.core.widget.NestedScrollView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.dialog.PayWayDialog;
import com.ckd.flyingtrip.javabean.CarBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CarDetailActivity extends BaseActivity {

    @BindView(R.id.activity_car_detail_nestedScrollView)
    NestedScrollView scrollView;
    @BindView(R.id.activity_car_detail_titleRl)
    RelativeLayout titleRl;
    @BindView(R.id.activity_car_detail_titleView)
    View titleView;
    @BindView(R.id.activity_car_detail_icon)
    ImageView icon;
    @BindView(R.id.activity_car_detail_name)
    TextView name;
    @BindView(R.id.activity_car_detail_money)
    TextView money;
    @BindView(R.id.activity_car_detail_lave)
    TextView lave;
    @BindView(R.id.activity_car_detail_description)
    TextView description;
    @BindView(R.id.activity_car_detail_address)
    TextView address;
    @BindView(R.id.activity_car_detail_buy)
    TextView buy;
    @BindView(R.id.activity_car_detail_banner)
    XBanner xBanner;
    @BindView(R.id.activity_car_detail_mapView)
    MapView mapView;

    private BaiduMap baiduMap;
    private UiSettings mUiSettings;

    private CarBean carBean;

    private PayWayDialog.Builder pb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_detail);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();

    }

    private void initView() {
        xBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                CarBean.IMGBean imgBean = (CarBean.IMGBean) model;
                Glide.with(CarDetailActivity.this).load(imgBean.getBicyclePictureUrl()).into((ImageView) view);
            }
        });
        List<CarBean.IMGBean> data = new ArrayList<>();
        xBanner.setBannerData(data);

        baiduMap = mapView.getMap();
        mUiSettings = baiduMap.getUiSettings();
        mUiSettings.setAllGesturesEnabled(false);
        mapView.showZoomControls(false);
        mapView.showScaleControl(false);
        View child = mapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
    }

    private void initData() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.CARXIANGXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("车辆详情", s);

                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String data = json.getString("data");
                        carBean = new Gson().fromJson(data, CarBean.class);
                        xBanner.setAutoPlayAble(carBean.getIMG().size() > 1);
                        xBanner.setBannerData(carBean.getIMG());
                        Glide.with(CarDetailActivity.this).load(carBean.getBicyclePictureUrl()).into(icon);
                        name.setText(carBean.getBicycle_name());
                        lave.setText("剩余：" + carBean.getBicycle_surplus() + "辆");
                        address.setText(carBean.getBicycle_extract_address());
                        switch (carBean.getUsed_type()) {
                            case "0":
                                buy.setText("立即租车");
                                money.setText("¥" + carBean.getBicycle_rent() + "/" + carBean.getBicycle_use_days() + "天");
                                description.setText("本车押金：¥" + carBean.getBicycleDeposit() +
                                        "\n租金是否可退：" + (carBean.getBicycle_refund_flg().equals("0") ? "不可退" : "可退") +
                                        "\n车辆描述：" + carBean.getBicycle_describe() +
                                        "\n使用电池型号：" + carBean.getBicycleBattery() +
                                        "\n联系电话：" + carBean.getSitePhone());
                                lave.setVisibility(View.GONE);
                                break;
                            case "1":
                                buy.setText("立即买车");
                                money.setText("¥" + carBean.getBicycle_price());
                                description.setText("车辆描述：" + carBean.getBicycle_describe() +
                                        "\n使用电池型号：" + carBean.getBicycleBattery() +
                                        "\n联系电话：" + carBean.getSitePhone());
                                lave.setVisibility(View.VISIBLE);
                                break;
                        }

                        LatLng l = new LatLng(Double.parseDouble(carBean.getSiteLatitude()), Double.parseDouble(carBean.getSiteLongitude()));
                        View view_mark = LayoutInflater.from(CarDetailActivity.this).inflate(R.layout.layout_map_maker, null);
                        ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
                        ivBattery.setImageResource(R.mipmap.main2);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
                        MarkerOptions options = new MarkerOptions().icon(bitmap).position(l);
                        Marker mMarkerA = (Marker) (baiduMap.addOverlay(options));
                        mMarkerA.setPerspective(true);
                        mMarkerA.setToTop();
                        mMarkerA.setFlat(true);
                        options.zIndex(999);

                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.target(l).zoom(16);
                        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(builder.build());
                        baiduMap.animateMapStatus(mapStatusUpdate);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("bicycleId", getIntent().getStringExtra("id"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initListener() {
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == 0) {
                    titleView.setVisibility(View.INVISIBLE);
                    titleView.setAlpha(0);
                } else {
                    titleView.setVisibility(View.VISIBLE);
                    float f = (float) scrollY / (xBanner.getHeight() - titleView.getHeight());
                    titleView.setAlpha(f);
                }
            }
        });
    }

    @OnClick({R.id.activity_car_detail_back, R.id.activity_car_detail_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_car_detail_back:
                finish();
                break;
            case R.id.activity_car_detail_buy:
                if (BcUtils.getUserInfo().getUserState().equals("2")) {
                    toast("请先实名认证！");
                    return;
                }
                switch (carBean.getUsed_type()) {
                    case "0":
                        buy.setText("立即租车");
                        Intent intent = new Intent(this, MyZhanghuActivity.class);
                        intent.putExtra("id", carBean.getBicycle_id());
                        intent.putExtra("code", carBean.getBindingElectricBicycle());
                        intent.putExtra("deposit", "¥" + carBean.getBicycleDeposit());
                        intent.putExtra("rent", "¥" + carBean.getBicycle_rent() + "/" + carBean.getBicycle_use_days() + "天");
                        startActivity(intent);
                        break;
                    case "1":
                        buy.setText("立即买车");
                        pb = new PayWayDialog.Builder(CarDetailActivity.this,
                                new PayWayDialog.Builder.PriorityListener() {
                                    @Override
                                    public void refreshPriorityUI(String f) {
                                        volleyQueryFei(carBean.getBicycle_id(), f);
                                        pb.create().dismiss();
                                    }
                                });
                        pb.create().show();
                        break;
                }
                break;
        }
    }

    private void volleyQueryFei(String id, String type) {
        if (type.equals("weixin")) {
//            Weixin weixin = new Weixin(GoumaiActivity.this, "");
//            weixin.volleyDINGDAN(id);
            dismisProgressDialog();
        } else if (type.equals("alipay")) {
            createLoadingDialog(this, "正在支付中...", true);
            Alipay alipay = new Alipay(CarDetailActivity.this, "");
            alipay.volleyQueryZhifu(id);
        }
    }
}
